<template>
  <div class="user-ban-container">
    <el-card class="ban-card">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.search"
              placeholder="请输入用户id"
              clearable
              @clear="handleReset"
            />
          </el-form-item>

          <el-form-item label="账号状态">
            <el-select v-model="searchForm.state" placeholder="请选择" style="width: 80px">
              <el-option label="全部" value="" />
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="私聊禁言状态">
            <el-select
              v-model="searchForm.privateChatState"
              placeholder="请选择"
              style="width: 120px"
            >
              <el-option label="全部" value="" />
              <el-option label="未禁言" value="0" />
              <el-option label="已禁言" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="群聊禁言状态">
            <el-select
              v-model="searchForm.groupChatState"
              placeholder="请选择"
              style="width: 120px"
            >
              <el-option label="全部" value="" />
              <el-option label="未禁言" value="0" />
              <el-option label="已禁言" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表区域 -->
      <div class="user-list-section">
        <!-- <h3>用户列表 (总数: {{ total }})</h3> -->

        <!-- 使用 Element Plus 的 v-loading 指令 -->
        <div v-loading="loading" element-loading-text="加载中" class="user-table-container">
          <!-- 表格头部 -->
          <div class="table-header" v-if="userList.length > 0">
            <div class="header-cell" style="flex: 1">用户ID</div>
            <div class="header-cell" style="flex: 1">账号</div>
            <div class="header-cell" style="flex: 1">昵称</div>
            <div class="header-cell" style="flex: 1">手机号</div>
            <div class="header-cell" style="flex: 1">状态</div>
            <div class="header-cell" style="flex: 1.5">私聊状态</div>
            <div class="header-cell" style="flex: 1.5">群聊状态</div>
            <div class="header-cell" style="flex: 1">私聊禁言时长</div>
            <div class="header-cell" style="flex: 1">群聊禁言时长</div>
            <div class="header-cell" style="flex: 2">操作</div>
          </div>

          <!-- 表格内容 -->
          <transition name="fade" mode="out-in">
            <div class="table-body" v-if="userList.length > 0" :key="loading">
              <div
                v-for="(user, index) in userList"
                :key="user.buyerUserId"
                class="table-row"
                :class="{ 'row-even': index % 2 === 0 }"
              >
                <div class="table-cell" style="flex: 1">{{ user.buyerUserId }}</div>
                <div class="table-cell" style="flex: 1">{{ user.account }}</div>
                <div class="table-cell" style="flex: 1">{{ user.name || '--' }}</div>
                <div class="table-cell" style="flex: 1">{{ user.phone || '--' }}</div>
                <div class="table-cell" style="flex: 1">
                  <el-tag :type="user.state === 1 ? 'success' : 'danger'">
                    {{ user.state === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </div>
                <div class="table-cell" style="flex: 1.5">
                  <el-tag
                    :type="
                      getPrivateChatStatus(user.privateChat) === '未禁言' ? 'success' : 'danger'
                    "
                  >
                    {{ getPrivateChatStatus(user.privateChat) }}
                  </el-tag>
                </div>
                <div class="table-cell" style="flex: 1.5">
                  <el-tag
                    :type="getGroupChatStatus(user.groupChat) === '未禁言' ? 'success' : 'danger'"
                  >
                    {{ getGroupChatStatus(user.groupChat) }}
                  </el-tag>
                </div>
                <div class="table-cell" style="flex: 1">{{
                  // 当privateChat为0时不回显privateChatTime
                  user.privateChat === 0 ? '-' : formatBanTime(user.privateChatTime)
                }}</div>
                <div class="table-cell" style="flex: 1">{{
                  // 当groupChat为0时不回显groupChatTime
                  user.groupChat === 0 ? '-' : formatBanTime(user.groupChatTime)
                }}</div>
                <div class="table-cell" style="flex: 2">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleBanClick(user)"
                    style="margin-right: 5px"
                  >
                    禁言
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    @click="handleUnbanC2CClick(user)"
                    style="margin-right: 5px"
                  >
                    单聊解除
                  </el-button>
                  <el-button type="warning" size="small" @click="handleUnbanGroupClick(user)">
                    群聊解除
                  </el-button>
                </div>
              </div>
            </div>
          </transition>

          <!-- 空数据状态 -->
          <transition name="fade" mode="out-in">
            <div v-if="userList.length === 0" class="empty-state" :key="!loading">
              <el-empty description="暂无用户数据" :image-size="120">
                <el-button type="primary" @click="loadUserList">重新加载</el-button>
              </el-empty>
            </div>
          </transition>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-scroll-wrapper">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination-wrapper"
          ></el-pagination>
        </div>
      </div>

      <!-- 禁言对话框 -->
      <el-dialog v-model="banDialogVisible" title="设置禁言" width="500px" class="ban-dialog">
        <div v-if="banTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ banTargetUser.buyerUserId }}
            <span v-if="banTargetUser.userAccount || banTargetUser.phone || banTargetUser.name">
              （{{ banTargetUser.userAccount || banTargetUser.phone || banTargetUser.name }}）
            </span>
          </div>
          <el-form :model="banDialogForm" label-width="120px" :rules="banFormRules" ref="banForm">
            <el-form-item label="禁言账号" prop="account">
              <el-input
                v-model="banDialogForm.account"
                placeholder="请输入用户账号"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item label="私聊禁言">
              <el-switch
                v-model="banDialogForm.enableC2C"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
            <el-form-item
              label="私聊禁言时长"
              prop="c2CmsgNospeakingTime"
              v-if="banDialogForm.enableC2C"
            >
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-input-number
                    v-model="banDialogForm.durationValue"
                    :min="1"
                    :max="999999"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="10">
                  <el-select v-model="banDialogForm.durationUnit" style="width: 100%">
                    <el-option label="分钟" value="minute" />
                    <el-option label="小时" value="hour" />
                    <el-option label="天" value="day" />
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="群聊禁言">
              <el-switch
                v-model="banDialogForm.enableGroup"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
            <el-form-item
              label="群聊禁言时长"
              prop="groupmsgNospeakingTime"
              v-if="banDialogForm.enableGroup"
            >
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-input-number
                    v-model="banDialogForm.groupDurationValue"
                    :min="1"
                    :max="999999"
                    controls-position="right"
                    style="width: 100%"
                  />
                </el-col>
                <el-col :span="10">
                  <el-select v-model="banDialogForm.groupDurationUnit" style="width: 100%">
                    <el-option label="分钟" value="minute" />
                    <el-option label="小时" value="hour" />
                    <el-option label="天" value="day" />
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="禁言原因">
              <el-input
                type="textarea"
                :rows="3"
                v-model="banDialogForm.reason"
                placeholder="请输入禁言原因（可选）"
              />
            </el-form-item>
          </el-form>
        </div>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="banDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="confirmBan">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 解除禁言对话框 -->
      <el-dialog v-model="unbanDialogVisible" title="设置禁言" width="500px" class="ban-dialog">
        <div v-if="unbanTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ unbanTargetUser.buyerUserId }}
            <span
              v-if="unbanTargetUser.userAccount || unbanTargetUser.phone || unbanTargetUser.name"
            >
              （{{ unbanTargetUser.userAccount || unbanTargetUser.phone || unbanTargetUser.name }}）
            </span>
          </div>
          <p class="confirm-text">确定要解除该用户的禁言状态吗？</p>
        </div>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="unbanDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="confirmUnban"
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>

      <!-- 单聊解除禁言对话框 -->
      <el-dialog
        v-model="unbanC2CDialogVisible"
        title="单聊解除禁言"
        width="500px"
        class="ban-dialog"
      >
        <div v-if="unbanC2CTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ unbanC2CTargetUser.buyerUserId }}
            <span
              v-if="
                unbanC2CTargetUser.userAccount ||
                unbanC2CTargetUser.phone ||
                unbanC2CTargetUser.name
              "
            >
              （{{
                unbanC2CTargetUser.userAccount ||
                unbanC2CTargetUser.phone ||
                unbanC2CTargetUser.name
              }}）
            </span>
          </div>
          <p class="confirm-text">确定要解除该用户的单聊禁言状态吗？</p>
        </div>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="unbanC2CDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="confirmUnbanC2C"
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>

      <!-- 群聊解除禁言对话框 -->
      <el-dialog
        v-model="unbanGroupDialogVisible"
        title="群聊解除禁言"
        width="500px"
        class="ban-dialog"
      >
        <div v-if="unbanGroupTargetUser">
          <div class="user-info">
            <strong>目标用户：</strong>ID {{ unbanGroupTargetUser.buyerUserId }}
            <span
              v-if="
                unbanGroupTargetUser.userAccount ||
                unbanGroupTargetUser.phone ||
                unbanGroupTargetUser.name
              "
            >
              （{{
                unbanGroupTargetUser.userAccount ||
                unbanGroupTargetUser.phone ||
                unbanGroupTargetUser.name
              }}）
            </span>
          </div>
          <p class="confirm-text">确定要解除该用户的群聊禁言状态吗？</p>
        </div>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="unbanGroupDialogVisible = false">取 消</el-button>
            <el-button type="primary" :loading="submitLoading" @click="confirmUnbanGroup"
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import { UserService } from '@/api/userApi'
  import { ElMessage } from 'element-plus'

  export default {
    name: 'UserBanManage',
    data() {
      return {
        submitLoading: false,
        loading: false,

        // 搜索表单数据
        searchForm: {
          search: '',
          state: '',
          privateChatState: '',
          groupChatState: ''
        },

        // 禁言对话框
        banDialogVisible: false,
        banTargetUser: null,
        banDialogForm: {
          account: '',
          enableC2C: true, // 是否启用单聊禁言
          durationValue: 1,
          durationUnit: 'hour',
          enableGroup: true, // 是否启用群聊禁言
          groupDurationValue: 1,
          groupDurationUnit: 'hour',
          reason: ''
        },
        banFormRules: {
          account: [{ required: true, message: '请输入用户账号', trigger: 'blur' }]
        },

        // 解除禁言对话框
        unbanDialogVisible: false,
        unbanTargetUser: null,

        // 单聊解除禁言对话框
        unbanC2CDialogVisible: false,
        unbanC2CTargetUser: null,

        // 群聊解除禁言对话框
        unbanGroupDialogVisible: false,
        unbanGroupTargetUser: null,

        // 用户列表相关
        userList: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableKey: 0
      }
    },

    mounted() {
      this.loadUserList()
    },

    methods: {
      // 格式化禁言时长显示
      formatBanTime(time) {
        // 如果时间是空对象，则显示 "-"
        if (!time || (typeof time === 'object' && Object.keys(time).length === 0)) {
          return '-'
        }

        // 如果时间是有效的字符串，则格式化显示
        if (typeof time === 'string' && time !== '') {
          // 解析日期时间
          const date = new Date(time)
          if (!isNaN(date.getTime())) {
            // 格式化为 YYYY-MM-DD HH:mm:ss
            return (
              date.getFullYear() +
              '-' +
              String(date.getMonth() + 1).padStart(2, '0') +
              '-' +
              String(date.getDate()).padStart(2, '0') +
              ' ' +
              String(date.getHours()).padStart(2, '0') +
              ':' +
              String(date.getMinutes()).padStart(2, '0') +
              ':' +
              String(date.getSeconds()).padStart(2, '0')
            )
          }
        }

        return '-'
      },

      // 获取私聊状态文本
      getPrivateChatStatus(status) {
        // 如果状态为 null 或 undefined，表示未禁言
        if (status === null || status === undefined) {
          return '未禁言'
        }
        // 0 表示未禁言，1 表示禁言
        return status === 0 ? '未禁言' : '禁言'
      },

      // 获取群聊状态文本
      getGroupChatStatus(status) {
        // 如果状态为 null 或 undefined，表示未禁言
        if (status === null || status === undefined) {
          return '未禁言'
        }
        // 0 表示未禁言，1 表示禁言
        return status === 0 ? '未禁言' : '禁言'
      },

      // 处理禁言点击
      handleBanClick(user) {
        console.log('handleBanClick:', user)
        if (!user) {
          this.$message({ type: 'error', message: '用户信息为空' })
          return
        }

        if (typeof user.buyerUserId !== 'number' || user.buyerUserId <= 0) {
          this.$message({ type: 'error', message: '用户ID无效' })
          return
        }

        this.openBanDialog(user)
      },

      openBanDialog(user) {
        console.log('openBanDialog:', user)
        this.banTargetUser = user
        this.banDialogForm.account = user.userAccount || user.phone || user.name || '未知用户'
        this.banDialogForm.durationValue = 1
        this.banDialogForm.durationUnit = 'hour'
        this.banDialogForm.groupDurationValue = 1
        this.banDialogForm.groupDurationUnit = 'hour'
        this.banDialogForm.reason = ''
        this.banDialogVisible = true
        console.log('弹窗已打开:', this.banDialogVisible)
      },

      // 处理解除禁言点击
      handleUnbanClick(user) {
        console.log('handleUnbanClick:', user)
        if (!user || !user.buyerUserId) {
          this.$message({ type: 'error', message: '用户信息不完整，无法执行解除禁言' })
          return
        }
        this.openUnbanDialog(user)
      },

      // 处理单聊解除禁言点击
      handleUnbanC2CClick(user) {
        console.log('handleUnbanC2CClick:', user)
        if (!user || !user.buyerUserId) {
          this.$message({ type: 'error', message: '用户信息不完整，无法执行单聊解除禁言' })
          return
        }
        this.openUnbanC2CDialog(user)
      },

      // 处理群聊解除禁言点击
      handleUnbanGroupClick(user) {
        console.log('handleUnbanGroupClick:', user)
        if (!user || !user.buyerUserId) {
          this.$message({ type: 'error', message: '用户信息不完整，无法执行群聊解除禁言' })
          return
        }
        this.openUnbanGroupDialog(user)
      },

      // 打开解除禁言对话框
      openUnbanDialog(user) {
        console.log('openUnbanDialog:', user)
        this.unbanTargetUser = user
        this.unbanDialogVisible = true
        this.$nextTick(() => {
          console.log('弹窗已打开:', this.unbanDialogVisible)
        })
      },

      // 打开单聊解除禁言对话框
      openUnbanC2CDialog(user) {
        console.log('openUnbanC2CDialog:', user)
        this.unbanC2CTargetUser = user
        this.unbanC2CDialogVisible = true
        this.$nextTick(() => {
          console.log('单聊解除禁言弹窗已打开:', this.unbanC2CDialogVisible)
        })
      },

      // 打开群聊解除禁言对话框
      openUnbanGroupDialog(user) {
        console.log('openUnbanGroupDialog:', user)
        this.unbanGroupTargetUser = user
        this.unbanGroupDialogVisible = true
        this.$nextTick(() => {
          console.log('群聊解除禁言弹窗已打开:', this.unbanGroupDialogVisible)
        })
      },

      // 计算禁言时长（转换为秒）
      calculateBanDuration(value, unit) {
        const unitMap = { minute: 60, hour: 3600, day: 86400 }
        return value * unitMap[unit]
      },

      // 确认禁言
      async confirmBan() {
        if (!this.banTargetUser) return

        this.$refs.banForm.validate(async (valid) => {
          if (!valid) return

          this.submitLoading = true
          try {
            // 计算单聊禁言时长（秒）
            let c2CDuration = 0
            if (this.banDialogForm.enableC2C) {
              c2CDuration = this.calculateBanDuration(
                this.banDialogForm.durationValue,
                this.banDialogForm.durationUnit
              )
            }

            // 计算群聊禁言时长（秒）
            let groupDuration = 0
            if (this.banDialogForm.enableGroup) {
              groupDuration = this.calculateBanDuration(
                this.banDialogForm.groupDurationValue,
                this.banDialogForm.groupDurationUnit
              )
            }

            // 判断是否禁言（只要有任意一个禁言时长大于0，就表示禁言）
            const isBanned = c2CDuration > 0 || groupDuration > 0 ? 1 : 0

            // 获取用户列表中的privateChatTime和groupChatTime字段值作为本地日期时间
            let privateChatTimeYMD = ''
            let groupChatTimeYMD = ''

            if (this.banTargetUser.privateChatTime) {
              // 直接使用用户列表中的日期时间字符串
              privateChatTimeYMD = this.banTargetUser.privateChatTime
            }

            if (this.banTargetUser.groupChatTime) {
              // 直接使用用户列表中的日期时间字符串
              groupChatTimeYMD = this.banTargetUser.groupChatTime
            }

            const params = {
              account: this.banTargetUser.buyerUserId.toString(), // 使用用户ID而不是账号
              stopSpeeckType: isBanned, // 是否禁言,1-是,0否
              c2CmsgNospeakingTime: c2CDuration, // 单聊禁言时长（秒）
              groupmsgNospeakingTime: groupDuration // 群聊禁言时长（秒）
              // 移除 c2CmsgNospeakingTimeYMD 和 groupmsgNospeakingTimeYMD 参数，因为后端已不再使用这些参数
            }

            console.log('禁言请求参数:', params)

            const response = await UserService.setUserBan(params)

            if ((response && response.code === '200') || response.code === 200) {
              this.$message({ type: 'success', message: response.message || '禁言设置成功' })
              this.banDialogVisible = false
              this.loadUserList()
            } else {
              this.$message({ type: 'error', message: response.message || '禁言设置失败' })
            }
          } catch (error) {
            console.error('操作失败:', error)
            let msg = '操作失败：网络错误'
            if (error.response && error.response.data) {
              msg = error.response.data.message || error.response.data.error || msg
            } else if (error.message) {
              msg = error.message
            }
            this.$message({ type: 'error', message: msg })
          } finally {
            this.submitLoading = false
          }
        })
      },

      // 确认解除禁言
      async confirmUnban() {
        if (!this.unbanTargetUser) return

        this.submitLoading = true
        try {
          // 根据要求修改参数传递方式
          const params = {
            account: this.unbanTargetUser.buyerUserId.toString(), // 使用用户ID而不是账号
            c2CmsgNospeakingTime: 0, // 用户禁言时长设为0
            groupmsgNospeakingTime: 0, // 用户组禁言时长设为0
            stopSpeeckType: 0 // 是否禁言,1-是,0否（解除所有禁言）
          }

          const response = await UserService.setUserUnban(params)

          // 严格检查 response 和 response.data
          if (!response) {
            this.$message({ type: 'error', message: '请求失败：未收到有效响应' })
            return
          }

          if (response.code === '200' || response.code === 200) {
            this.$message({ type: 'success', message: response.message || '解除禁言成功' })
            this.unbanDialogVisible = false
            this.loadUserList()
          } else {
            // 使用安全的属性访问方式
            const message = response.message
            this.$message({ type: 'error', message: message || '解除禁言失败' })
          }
        } catch (error) {
          console.error('操作失败:', error)
          let msg = '操作失败：网络错误'
          this.$message({ type: 'error', message: msg })
        } finally {
          this.submitLoading = false
        }
      },

      // 确认单聊解除禁言
      async confirmUnbanC2C() {
        if (!this.unbanC2CTargetUser) return

        this.submitLoading = true
        try {
          // 根据要求修改参数传递方式
          const params = {
            account: this.unbanC2CTargetUser.buyerUserId.toString(), // 使用用户ID而不是账号
            c2CmsgNospeakingTime: 0, // 用户禁言时长设为0，表示解除单聊禁言
            stopSpeeckType: this.unbanC2CTargetUser.groupChatTime ? 1 : 0 // 如果还有群聊禁言则为1，否则为0
            // 不传递 groupmsgNospeakingTime 参数，因为只解除单聊禁言
          }

          const response = await UserService.setUserUnban(params)

          if (!response) {
            this.$message({ type: 'error', message: '请求失败：未收到有效响应' })
            return
          }

          if (response.code === '200' || response.code === 200) {
            this.$message({ type: 'success', message: response.message || '单聊解除禁言成功' })
            this.unbanC2CDialogVisible = false
            this.loadUserList()
          } else {
            const message = response.message
            this.$message({ type: 'error', message: message || '单聊解除禁言失败' })
          }
        } catch (error) {
          console.error('操作失败:', error)
          let msg = '操作失败：网络错误'
          this.$message({ type: 'error', message: msg })
        } finally {
          this.submitLoading = false
        }
      },

      // 确认群聊解除禁言
      async confirmUnbanGroup() {
        if (!this.unbanGroupTargetUser) return

        this.submitLoading = true
        try {
          // 根据要求修改参数传递方式
          const params = {
            account: this.unbanGroupTargetUser.buyerUserId.toString(), // 使用用户ID而不是账号
            groupmsgNospeakingTime: 0, // 用户组禁言时长设为0，表示解除群聊禁言
            stopSpeeckType: this.unbanGroupTargetUser.privateChatTime ? 1 : 0 // 如果还有单聊禁言则为1，否则为0
            // 不传递 c2CmsgNospeakingTime 参数，因为只解除群聊禁言
          }

          const response = await UserService.setUserUnban(params)

          if (!response) {
            this.$message({ type: 'error', message: '请求失败：未收到有效响应' })
            return
          }

          if (response.code === '200' || response.code === 200) {
            this.$message({ type: 'success', message: response.message || '群聊解除禁言成功' })
            this.unbanGroupDialogVisible = false
            this.loadUserList()
          } else {
            const message = response.message
            this.$message({ type: 'error', message: message || '群聊解除禁言失败' })
          }
        } catch (error) {
          console.error('操作失败:', error)
          let msg = '操作失败：网络错误'
          this.$message({ type: 'error', message: msg })
        } finally {
          this.submitLoading = false
        }
      },

      // 查询用户列表
      async loadUserList() {
        this.loading = true
        try {
          const params = {
            page: this.currentPage,
            pageSize: this.pageSize,
            search: this.searchForm.search,
            state: this.searchForm.state,
            privateChatState: this.searchForm.privateChatState,
            groupChatState: this.searchForm.groupChatState
          }

          const response = await UserService.getUserBanList(params)

          if (response && (response.code === '200' || response.code === 200)) {
            const data = response.data

            let userList = []
            let total = 0

            if (data && data.list && Array.isArray(data.list)) {
              userList = data.list
            }

            if (data && typeof data.total === 'number') {
              total = data.total
            }

            this.userList = userList
            this.total = total
          } else {
            this.$message({ type: 'error', message: response?.message || '获取用户列表失败' })
          }
        } catch (error) {
          console.error('获取用户列表失败:', error)
          // 安全地访问错误信息
          let errorMsg = '获取用户列表失败'
          if (error) {
            if (typeof error === 'string') {
              errorMsg = error
            } else if (error.message) {
              errorMsg = error.message
            } else if (error.toString) {
              errorMsg = error.toString()
            }
          }
          this.$message({ type: 'error', message: errorMsg })
        } finally {
          this.loading = false
        }
      },

      // 处理搜索
      handleSearch() {
        this.currentPage = 1
        this.loadUserList()
      },

      // 处理重置
      handleReset() {
        this.searchForm.search = ''
        this.searchForm.state = ''
        this.searchForm.privateChatState = ''
        this.searchForm.groupChatState = ''
        this.currentPage = 1
        this.loadUserList()
      },

      // 处理分页大小变化
      handleSizeChange(val) {
        this.pageSize = val
        this.currentPage = 1
        this.loadUserList()
      },

      // 处理当前页变化
      handleCurrentChange(val) {
        this.currentPage = val
        this.loadUserList()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .user-ban-container {
    padding: 20px;

    .ban-card {
      .search-section {
        margin-bottom: 20px;
      }

      .user-list-section {
        h3 {
          margin-bottom: 15px;
          font-size: 16px;
          font-weight: bold;
        }

        .user-table-container {
          border: 1px solid #ebeef5;
          border-radius: 4px;
          overflow: hidden;
          overflow-x: auto; /* 添加横向滚动条 */
          position: relative;

          /* 添加过渡效果 */
          &.v-loading {
            transition: opacity 0.3s ease;
          }

          .table-header {
            display: flex;
            background-color: #f5f7fa;
            border-bottom: 1px solid #ebeef5;
            min-width: 1200px; /* 设置最小宽度 */

            .header-cell {
              padding: 12px 10px;
              font-weight: bold;
              border-right: 1px solid #ebeef5;
              box-sizing: border-box;
              font-size: 14px;

              &:last-child {
                border-right: none;
              }
            }
          }

          .table-body {
            min-width: 1200px; /* 设置最小宽度 */

            .table-row {
              display: flex;
              border-bottom: 1px solid #ebeef5;

              &:last-child {
                border-bottom: none;
              }

              &.row-even {
                background-color: #fafafa;
              }

              .table-cell {
                padding: 12px 10px;
                border-right: 1px solid #ebeef5;
                box-sizing: border-box;
                word-break: break-all;
                display: flex;
                align-items: center;
                font-size: 14px;

                &:last-child {
                  border-right: none;
                }

                /* 操作按钮容器 */
                &:last-child {
                  .el-button {
                    margin-right: 5px;

                    &:last-child {
                      margin-right: 0;
                    }
                  }
                }
              }
            }
          }
        }

        .empty-state {
          text-align: center;
          padding: 40px 0;
        }

        .pagination-wrapper {
          margin-top: 20px;
          text-align: right;
          
          /* 确保页码字体样式与用户信息界面保持一致 */
          :deep(.el-pagination) {
            font-weight: normal;
          }
          
          :deep(.el-pagination .el-pager li) {
            font-weight: normal;
          }
          
          :deep(.el-pagination .el-pager li.active) {
            font-weight: bold;
          }
          
          /* 添加更多样式确保与用户信息界面一致 */
          :deep(.el-pagination .el-pager li:hover) {
            color: #409eff;
          }
          
          :deep(.el-pagination .el-pager li.active:hover) {
            color: #fff;
          }
        }

        /* 分页滚动容器样式 */
        .pagination-scroll-wrapper {
          width: 100%;
          overflow-x: auto;
          -webkit-overflow-scrolling: touch;
          margin-top: 20px;
          padding: 5px 0;
          box-sizing: border-box;
          /* 创建独立的滚动上下文 */
          contain: content;
        }

        /* 自定义滚动条样式 */
        .pagination-scroll-wrapper::-webkit-scrollbar {
          height: 6px;
        }

        .pagination-scroll-wrapper::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 3px;
        }

        .pagination-scroll-wrapper::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 3px;
        }

        .pagination-scroll-wrapper::-webkit-scrollbar-thumb:hover {
          background: #a8a8a8;
        }

        /* 移动端分页容器额外样式 */
        @media screen and (max-width: 768px) {
          .pagination-scroll-wrapper {
            padding: 10px 0;
          }

          .pagination-wrapper {
            text-align: right;
            white-space: nowrap;
          }
        }
      }
    }

    .ban-dialog {
      .user-info {
        margin-bottom: 20px;
        font-size: 14px;
      }

      .confirm-text {
        margin-bottom: 0;
        font-size: 14px;
      }
    }
  }

  /* Element Plus 加载样式自定义 */
  :deep(.el-loading-mask) {
    background-color: rgba(255, 255, 255, 0.9);
    transition: opacity 0.3s ease;
  }

  :deep(.el-loading-spinner) {
    transition: transform 0.3s ease;
  }

  :deep(.el-loading-spinner .el-loading-text) {
    color: #409eff;
    font-size: 14px;
    margin-top: 10px;
  }

  /* 添加淡入淡出效果 */
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s ease;
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
</style>
